﻿using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Events;

namespace Luka;

/// <summary>
/// 日志操作类
/// </summary>
[NotScanned]
public static class LogSetup
{
    //所有日志级别
    private static readonly string[] LogLevel = { "Verbose", "Debug", "Information", "Warning", "Error", "Fatal" };

    //存储日志文件的格式(固定不可变)
    private static readonly string OutputTemplate = "{Timestamp:HH:mm} || {Level} || {SourceContext:l} || {Message} || {Exception} ||end {NewLine}";

    //日志存储路径
    public static string LogFilePath(string LogEvent) => $@"{AppContext.BaseDirectory}Logs\{LogEvent}\log.log";

    /// <summary>
    /// 日志
    /// </summary>
    public static IHostBuilder AddLog(this IHostBuilder builder)
    {
        var setting = InternalApp.GetSection<LogOptions>("Logs");
        //初始化
        var log = new LoggerConfiguration();
        //过滤微软的日志
        log.MinimumLevel.Override("Microsoft", LogEventLevel.Information);
        //注册日志上下文
        log.Enrich.FromLogContext();
        //输出到控制台-自定义模板
        log.WriteTo.Async(a => a.Console(outputTemplate: "{NewLine}[{Level}]：{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}{NewLine}Message：{Message:lj}{NewLine}{Exception}"));
        //日志分级保存
        if (setting?.FileLog != null && setting.FileLog?.IsEnable == true)
        {
            if (setting.FileLog?.LogLevel != null && setting.FileLog.LogLevel.Length > 0)
            {
                foreach (var item in setting.FileLog.LogLevel.Where(it => !string.IsNullOrWhiteSpace(it) && LogLevel.Contains(it)))
                {
                    //日志文件路径
                    string path = setting.FileLog.IsClassify == true ? LogFilePath(item) : $"{AppContext.BaseDirectory}Logs/.log";
                    //写入日志
                    log.WriteTo.Async(a => a.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level.ToString() == item).WriteTo.File(path, rollingInterval: RollingInterval.Day, outputTemplate: OutputTemplate)));
                }
            }
        }
        //清除内置日志框架
        Log.Logger = log.CreateLogger();
        //使用中间件
        builder.UseSerilog();

        return builder;
    }
}